﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.Design;
using System.Security.Claims;
using T.Materials.API.Application.Command.MaterialRequisitionCommand;
using T.Materials.Domain.Model;
using T.Materials.Repository;
using T.Materials.Repository.MaterialsInterface;

namespace T.Materials.API.Application.CommandHandler.MaterialRequisitionCommandHandler
{
    /// <summary>
    /// 物资领用命令处理器
    /// </summary>
    public class AddMaterialRequisitionCommandHandler : IRequestHandler<AddMaterialRequisitionCommand, int>
    {
        /// <summary>
        /// 物资领用仓储接口
        /// </summary>
        protected readonly IMaterialRequisitionRepository materialRequisitionRepository;

        /// <summary>
        /// 上下文
        /// </summary>
        protected readonly MEFDbContext mEFDbContext;

        /// <summary>
        /// 物资仓库接口
        /// </summary>
        protected readonly IMaterialStoreRepository materialStoreRepository;

        /// <summary>
        /// 存储物资领用存储仓储接口
        /// </summary>
        protected readonly IStorageMaterialsRepository storageMaterialsRepository;

        /// <summary>
        /// 映射器
        /// </summary>
        //protected readonly IMapper mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="storageMaterialsRepository">存储物资领用存储仓储接口</param>
        /// <param name="materialRequisitionRepository">物资领用仓储接口</param>
        /// <param name="mEFDbContext">上下文</param>
        /// <param name="materialStoreRepository">物资仓库接口</param>
        /// <param name="mapper">映射器</param>
        public AddMaterialRequisitionCommandHandler(IMaterialRequisitionRepository materialRequisitionRepository, MEFDbContext mEFDbContext, IMaterialStoreRepository materialStoreRepository, IStorageMaterialsRepository storageMaterialsRepository)
        {
            this.materialRequisitionRepository = materialRequisitionRepository;
            this.mEFDbContext = mEFDbContext;
            this.materialStoreRepository = materialStoreRepository;
            //this.mapper = mapper;
            this.storageMaterialsRepository = storageMaterialsRepository;
        }

        /// <summary>
        /// 物资领用命令处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<int> Handle(AddMaterialRequisitionCommand request, CancellationToken cancellationToken)
        {
            var strategy = mEFDbContext.Database.CreateExecutionStrategy();

            return await strategy.ExecuteAsync(async () =>
            {
                using (var transaction = mEFDbContext.Database.BeginTransaction())
                {
                    try
                    {
                        // 库存不足检查
                        foreach (var item in request.materialRequisitionDtos)
                        {
                            var res = await materialStoreRepository.GetModelAsync(item.MaterialStoreId);
                            if (res.MaterialClassificat == 2)
                            {
                                if (res == null || res.Number < item.QuantityReceived)
                                {
                                    return -1;
                                }
                            }
                        }

                        // 新增领用单
                        MaterialRequisition madd = new MaterialRequisition
                        {
                            // 初始化属性...
                            CompanyID = request.CompanyID,
                            User_Id = request.User_Id,
                            MaterialStoreId=request.MaterialStoreId,
                            Title = request.Title,
                            UsageDescription = request.UsageDescription,
                            Recipient = request.Recipient,
                            MaterialRequisitNotes = request.MaterialRequisitNotes,
                            CollectionDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")),
                            ApprovalStatus = request.ApprovalStatus,
                            Approver = "",
                            CreatedBy = request.CreatedBy,
                            CreatedDate = DateTime.Now
                        };

                        await materialRequisitionRepository.AddAsync(madd);

                        // 新增领用明细
                        foreach (var item in request.materialRequisitionDtos)
                        {
                            StorageMaterials storage = new StorageMaterials
                            {
                                // 初始化属性...
                                MaterialRequisitionId = madd.MaterialRequisitionId,
                                MaterialStoreId = item.MaterialStoreId,
                                QuantityReceived = item.QuantityReceived,//领用数量
                                CompanyID = request.CompanyID,
                                User_Id = request.User_Id,
                                CreatedBy = request.CreatedBy,
                                CreatedDate = DateTime.Now,
                            };

                            await storageMaterialsRepository.AddAsync(storage);
                        }

                        // 更新库存
                        foreach (var item in request.materialRequisitionDtos)
                        {
                            var res = await materialStoreRepository.GetModelAsync(item.MaterialStoreId);
                            if (res.MaterialClassificat == 2)
                            {
                                res.Number -= item.QuantityReceived;
                                await materialStoreRepository.UpdateAsync(res);
                            }
                        }

                        // 提交事务
                        transaction.Commit();
                        return 1;
                    }
                    catch (Exception)
                    {
                        // 回滚事务
                        transaction.Rollback();

                        throw;
                    }
                }
            });
        }


        //    public async Task<int> Handle(AddMaterialRequisitionCommand request, CancellationToken cancellationToken)
        //    {           

        //    //    //事务处理
        //    //    using (var transaction = mEFDbContext.Database.BeginTransaction())
        //    //    {
        //    //        try
        //    //        {
        //    //            //库存不足
        //    //            foreach (var item in request.materialRequisitionDtos)
        //    //            {
        //    //                var res = await materialStoreRepository.GetModelAsync(item.MaterialStoreId);
        //    //                if (res == null || res.Number < item.QuantityReceived)
        //    //                {
        //    //                    return -1;
        //    //                }
        //    //            }

        //    //            //新增领用单
        //    //            MaterialRequisition madd = new MaterialRequisition()
        //    //            {
        //    //                CompanyID = request.CompanyID,
        //    //                User_Id = request.User_Id,
        //    //                Title = request.Title,
        //    //                UsageDescription = request.UsageDescription,
        //    //                Recipient = request.Recipient,
        //    //                MaterialRequisitNotes = request.MaterialRequisitNotes,
        //    //                CollectionDate = DateTime.Now,
        //    //                ApprovalStatus = request.ApprovalStatus,
        //    //                Approver = "",
        //    //                                        CreatedBy = request.CreatedBy,
        //    //                CreatedDate = DateTime.Now
        //    //            };

        //    //            //更新数据库
        //    //            await materialRequisitionRepository.AddAsync(madd);

        //    //            //新增领用明细
        //    //            foreach (var item in request.materialRequisitionDtos)
        //    //            {
        //    //                StorageMaterials storage = new StorageMaterials()
        //    //                {
        //    //                    MaterialRequisitionId = madd.MaterialRequisitionId,
        //    //                    MaterialStoreId = item.MaterialStoreId,
        //    //                    QuantityReceived = item.QuantityReceived,
        //    //                    CompanyID = request.CompanyID,
        //    //                    User_Id = request.User_Id,
        //    //                    CreatedBy = request.CreatedBy,
        //    //                    CreatedDate = DateTime.Now,
        //    //                };
        //    //                //更新数据库
        //    //                await storageMaterialsRepository.AddAsync(storage);
        //    //            }

        //    //            //更新库存
        //    //            foreach (var item in request.materialRequisitionDtos)
        //    //            {
        //    //                var res = await materialStoreRepository.GetModelAsync(item.MaterialStoreId);
        //    //                res.Number -= item.QuantityReceived;
        //    //                await materialStoreRepository.UpdateAsync(res);
        //    //            }

        //    //            //提交事务
        //    //            transaction.Commit();
        //    //            return 1;
        //    //        }
        //    //        catch (Exception)
        //    //        {
        //    //            //回滚事务
        //    //            transaction.Rollback();

        //    //            throw;
        //    //        }
        //    //    }
        //    //}
        //}
    }
}